<template>
  <div id="dialog">
    <div @click="centerDialogVisible = true" class="el-icon-camera cameraIconfont"></div>
    <el-dialog title="上传图片" :visible.sync="centerDialogVisible" width="950px">
      <div class="content">
        <div class="left">
          <div class="input">
            <el-input
              placeholder="选择分类"
              suffix-icon="el-icon-search"
              v-model="input1"
            >
            </el-input>
          </div>
          <div class="tree">
            <el-tree
              :data="data"
              :props="defaultProps"
              @node-click="handleNodeClick"
            ></el-tree>
          </div>
        </div>
        <div class="right">
          <div class="top-menu">
            <el-button type="primary" size="mini" @click="upImg">使用选中图片</el-button>
            <el-button
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="uoLode"
            ></el-button>
            <form enctype="multipart/form-data" method="post" style="display: none">
              <input type="file" @change="realClick" ref="inputFile" />
            </form>

            <el-button
              type="danger"
              @click="delImg"
              icon="el-icon-delete"
              size="mini"
            ></el-button>
            <div class="input">
              <el-cascader
                :options="options"
                @change="handleChange"
                size="mini"
              ></el-cascader>
            </div>

            <div class="radio">
              <el-radio-group v-model="radio2" size="mini">
                <el-radio-button label="图片"></el-radio-button>
                <el-radio-button label="视频"></el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div class="body">
            <div
              v-for="(item, index) in imgList"
              :key="index"
              :class="['image', { activeimg: imgIndex.indexOf(index) != -1 }]"
              @click="img_click(index)"
              :data-once="true"
            >
              <img :src="item.sattDir" alt="" />
              <span v-show="imgIndex.indexOf(index) != -1" class="count">{{
                imgIndex.indexOf(index) + 1
              }}</span>
            </div>
          </div>
          <div class="bottom">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage4"
              :page-sizes="[10]"
              :page-size="100"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入axios
import { treeList } from "@/network/api/store/sort";
import { attachmentList, deleteImg, move, uploadImg } from "@/network/api/store/index";
export default {
  data() {
    return {
      centerDialogVisible: false,
      input1: "",
      defaultProps: {
        children: "children",
        label: "label",
      },
      options: [
        {
          value: 123,
          label: "指南",
          children: [
            {
              value: 222,
              label: "aa",
            },
          ],
        },
      ],
      radio2: "图片",
      defaultProps: {
        children: "children",
        label: "label",
      },
      data: [], //侧边栏列表
      imgList: [], //图片列表
      imgIndex: [], //用来存储该图片的下标
      currentPage4: 1, //当前页
      total: 0, //总条数
      id: 0, //数据id
      attId: [], //选中图片的id
    };
  },
  methods: {
    async handleNodeClick(data) {
      let { id } = data;
      this.id = id;
      let res = await attachmentList(id, 1, 10);
      let list = res.data.data.list;
      this.imgList = [...list];
      this.total = res.data.data.total;
      this.imgIndex = [];
      console.log(id, res.data.data);
      // console.log(data, id);
    },
    async handleChange(value) {
      let ids = value.slice(-1)[0];
      let { attId, id } = this.$data;
      let str;
      if (attId.length == 1) {
        str = String(attId[0]);
        console.log(str);
      } else {
        str = attId.join(",");
      }
      let mo = await move(str, ids);
      console.log(mo);
      let res = await attachmentList(id, 1, 10);
      let list = res.data.data.list;
      this.imgList = [...list];
      this.total = res.data.data.total;
      this.imgIndex = [];
      this.$message({
        type: "success",
        message: "移动完成!",
      });
      console.log(123, id);
    },
    // 数据处理函数
    datadispose(data) {
      let arr = [];
      data.forEach((item) => {
        let obj = {
          label: item.name,
          id: item.id,
          value: item.id,
        };
        if (item.child && item.child.length != 0) {
          obj.children = this.datadispose(item.child);
        }
        arr.push(obj);
      });
      return arr;
    },

    img_click(index) {
      let { imgIndex, attId, imgList } = this.$data;
      // console.log(imgList);
      // 判断数组中是否有该下表存在
      if (imgIndex.indexOf(index) == -1) {
        imgIndex.push(index);
        attId.push(imgList[index].attId);
      } else {
        attId.splice(imgIndex.indexOf(index), 1);
        imgIndex.splice(imgIndex.indexOf(index), 1);
      }

      this.imgIndex = [...imgIndex];
      this.attId = [...attId];
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    // 分页
    async handleCurrentChange(val) {
      let id = this.id;
      let res = await attachmentList(id, val, 10);
      let list = res.data.data.list;
      this.imgList = [...list];

      this.imgIndex = [];
      console.log(`当前页: ${val}`);
    },
    // 上传图片
    upImg() {
      let imgarr = [];
      let { imgIndex, imgList } = this.$data;
      // 遍历选中图片的下表数组
      imgIndex.forEach((index) => {
        imgarr.push(imgList[index].sattDir);
      });
      console.log(imgarr);
      if (imgarr.length != 0) {
        this.$emit("send", imgarr);
        this.centerDialogVisible = false;
      }
    },
    delImg() {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let { attId, id } = this.$data;
          let msg = await deleteImg(attId.join(","));
          let res = await attachmentList(id, 1, 10);
          let list = res.data.data.list;
          this.imgList = [...list];
          this.total = res.data.data.total;
          this.imgIndex = [];
          console.log(attId.join(","));
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 本地上传文件
    uoLode() {
      // console.log(this.$refs.inputFile.$el);
      this.$refs.inputFile.dispatchEvent(new MouseEvent("click"));

      // this.$refs.inputFile.$el.click();
    },
    // 文件域点击
    async realClick(e) {
      let { id } = this.$data;
      let file = e.target.files[0];
      console.log(file);
      // 创建from对象
      let formdata = new FormData();
      formdata.append("multipart", file);
      console.log(formdata);
      let res = await uploadImg(id, formdata);
      // console.log(res., 2222222222);
      if (res.data.code === 200) {
        let ress = await attachmentList(id, 1, 10);
        let list = ress.data.data.list;
        this.imgList = [...list];
        this.total = ress.data.data.total;
        this.imgIndex = [];
        this.$message({
          type: "success",
          message: "图片上传成功!",
        });
      } else {
        this.$message({
          type: "success",
          message: "图片上传失败!",
        });
      }
    },
  },
  async created() {
    let res = await treeList(-1, "", 2);
    let list = this.datadispose(res.data.data);
    let options = this.datadispose(res.data.data);
    this.data = [...list];
    this.options = [...options];
    console.log("res", this.data);
  },
};
</script>
<style lang="scss">
.cameraIconfont {
  position: relative;
  top: -23px;
  width: 58px;
  height: 58px;
  background: #fafafa;
  text-align: center;
  line-height: 58px;
  border: 1px solid #aaa;
  border-radius: 5px;
  cursor: pointer;
}

#dialog {
  .content {
    display: flex;
    .left {
      width: 242px;
      .tree {
        .custom-tree-node-label {
          color: #4386c6 !important;
        }
      }
    }
    .right {
      flex: 1;
      .top-menu {
        display: flex;
        align-items: center;
      }
      .radio {
        position: relative;
        top: -2px;
        left: 20px;
      }
      .input {
        position: relative;
        left: 10px;
      }
      .body {
        margin-top: 30px;
        height: 280px;
        .image {
          width: 110px;
          height: 110px;
          display: inline-block;
          margin: 20px 10px;
          position: relative;
          img {
            width: 110px;
            height: 110px;
          }
          .count {
            display: inline-block;
            width: 20px;
            height: 20px;
            background: #4386c6;
            line-height: 20px;
            text-align: center;
            font-weight: 700;
            border-radius: 50%;
            position: absolute;
            bottom: 5px;
            right: 5px;
            color: #fff;
          }
        }
      }
      .bottom {
        margin-top: 30px;
        position: relative;
        top: 50px;
        left: 60px;
      }
    }
  }
}
.activeimg {
  outline: 1px solid #4386c6;
}
</style>
